<!-- <route lang="json5" type="page">
  {
    style: {
      navigationBarTitleText: '配音详情',
    },
  }
</route> -->

<template>
  <view class="dubbing-detail-container">
    <!-- 绘本信息卡片 -->
    <view class="book-info-card" v-if="detailData">
      <view class="book-cover">
        <image class="cover-image" :src="detailData.coverUrl" mode="aspectFill" lazy-load />
      </view>
      <view class="book-info">
        <text class="book-title">{{ detailData.bookTitle }}</text>
        <view class="progress-info">
          <text class="progress-text">配音进度：{{ detailData.recordedPages }}/{{ detailData.totalPages }}页</text>
          <view class="progress-bar">
            <view class="progress-fill" :style="{ width: detailData.completionPercentage + '%' }"></view>
          </view>
          <text class="progress-percentage">{{ detailData.completionPercentage }}%</text>
        </view>
        <view class="public-setting">
          <text class="setting-label">公开设置：</text>
          <switch 
            :checked="detailData.allShareable" 
            @change="onPublicSettingChange"
            color="#42bbff"
          />
          <view class="share-btn" @click="shareRecording">
            <uni-icons type="redo" size="18" color="#42bbff"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 页面配音列表 -->
    <view class="page-list" v-if="detailData && detailData.pageRecordings">
      <view 
        v-for="page in detailData.pageRecordings" 
        :key="page.pageId" 
        class="page-item"
        :class="{ active: currentPageId === page.pageId }"
        @click="selectPage(page)"
      >
        <view class="page-number">{{ page.pageNumber }}</view>
        <view class="page-status">
          <uni-icons 
            v-if="page.hasRecording" 
            type="checkmarkempty" 
            size="16" 
            color="#32cd32"
          ></uni-icons>
          <uni-icons 
            v-else 
            type="circle" 
            size="16" 
            color="#ccc"
          ></uni-icons>
        </view>
      </view>
    </view>

    <!-- 当前页面详情 -->
    <view class="current-page-detail" v-if="currentPage">
      <view class="page-image">
        <image class="page-img" :src="currentPage.imageUrl" mode="aspectFit" lazy-load />
      </view>
      
      <view class="page-text" v-if="currentPage.textContent">
        <text class="text-content">{{ currentPage.textContent }}</text>
      </view>

      <!-- 配音控制区域 -->
      <view class="recording-controls" v-if="currentPage.hasRecording">
        <view class="recording-info">
          <text class="duration">时长：{{ currentPage.formattedDuration || '00:00' }}</text>
          <text class="score" v-if="currentPage.score">评分：{{ currentPage.score }}分</text>
          <text class="record-time">录制于：{{ formatRecordTime(currentPage.recordTime) }}</text>
        </view>
        
        <view class="audio-controls">
          <view class="play-btn" @click="togglePlay">
            <wd-icon
              :name="isPlaying ? 'pause' : 'play'"
              size="26px"
              color="#fff"
            ></wd-icon>

          </view>
          <view class="progress-container">
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: audioProgress + '%' }"></view>
            </view>
            <text class="time-text">{{ formatTime(currentTime) }} / {{ formatTime(totalTime) }}</text>
          </view>
        </view>
      </view>

      <!-- 无配音提示 -->
      <view class="no-recording" v-else>
        <text class="no-recording-text">该页面暂无配音</text>
        <text class="no-recording-hint">可在绘本阅读页面进行录制</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 分享Canvas组件 -->
    <DubbingShareCanvas
      ref="shareCanvasRef"
      :visible="showShareCanvas"
      :dubbing-data="detailData"
      :user-info="userInfo"
      share-type="detail"
      @generated="onShareCardGenerated"
      @error="onShareCardError"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad, onShow, onShareAppMessage } from '@dcloudio/uni-app'
import {
  getUserRecordingDetailPage,
  setBookRecordingsPublic,
  generateBookRecordingShare
} from '@/api/recording'
import type {
  UserRecordingDetailPageRespVO,
  PageRecordingVO,
  UserRecordingPublicSettingReqVO
} from '@/api/types/recording'
import DubbingShareCanvas from '@/components/DubbingShareCanvas.vue'

// 页面参数
const bookId = ref<number>(0)
const bookTitle = ref<string>('')

// 详情数据
const detailData = ref<UserRecordingDetailPageRespVO | null>(null)
const loading = ref(false)

// 当前选中的页面
const currentPageId = ref<number>(0)
const currentPage = computed(() => {
  if (!detailData.value || !currentPageId.value) return null
  return detailData.value.pageRecordings.find(p => p.pageId === currentPageId.value) || null
})

// 音频播放状态
const isPlaying = ref(false)
const audioProgress = ref(0)
const currentTime = ref(0)
const totalTime = ref(0)
let audioContext: UniApp.InnerAudioContext | null = null

// 分享相关状态
const showShareCanvas = ref(false)
const shareImageUrl = ref('')
const shareCanvasRef = ref()
const userInfo = ref({ nickname: '小配音员', avatar: '' })

// 页面加载
onLoad((options: any) => {
  if (options.bookId) {
    bookId.value = parseInt(options.bookId)
  }
  if (options.title) {
    bookTitle.value = decodeURIComponent(options.title)
    // 动态设置导航栏标题
    uni.setNavigationBarTitle({
      title: bookTitle.value || '配音详情'
    })
  }
})

onShow(() => {
  if (bookId.value) {
    loadDetailData()
  }
})

// 加载详情数据
const loadDetailData = async () => {
  if (loading.value) return

  try {
    loading.value = true
    const response = await getUserRecordingDetailPage(bookId.value)
    
    if (response.code === 0 && response.data) {
      detailData.value = response.data
      
      // 默认选中第一页
      if (detailData.value.pageRecordings.length > 0) {
        currentPageId.value = detailData.value.pageRecordings[0].pageId
      }
    }
  } catch (error) {
    console.error('加载配音详情失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}



// 选择页面
const selectPage = (page: PageRecordingVO) => {
  currentPageId.value = page.pageId
  
  // 停止当前音频播放
  if (audioContext) {
    audioContext.stop()
    audioContext.destroy()
    audioContext = null
    isPlaying.value = false
  }
}

// 切换播放状态
const togglePlay = () => {
  if (!currentPage.value || !currentPage.value.hasRecording) return
  
  if (isPlaying.value) {
    pauseAudio()
  } else {
    playAudio()
  }
}

// 播放音频
const playAudio = () => {
  if (!currentPage.value || !currentPage.value.audioUrl) return
  
  if (!audioContext) {
    audioContext = uni.createInnerAudioContext()
    audioContext.src = currentPage.value.audioUrl
    
    audioContext.onPlay(() => {
      isPlaying.value = true
    })
    
    audioContext.onPause(() => {
      isPlaying.value = false
    })
    
    audioContext.onEnded(() => {
      isPlaying.value = false
      audioProgress.value = 0
      currentTime.value = 0
    })
    
    audioContext.onTimeUpdate(() => {
      if (audioContext) {
        currentTime.value = audioContext.currentTime
        totalTime.value = audioContext.duration
        audioProgress.value = (currentTime.value / totalTime.value) * 100
      }
    })
  }
  
  audioContext.play()
}

// 暂停音频
const pauseAudio = () => {
  if (audioContext) {
    audioContext.pause()
  }
}

// 公开设置变更
const onPublicSettingChange = async (event: any) => {
  const isPublic = event.detail.value
  
  try {
    const data: UserRecordingPublicSettingReqVO = {
      bookId: bookId.value,
      isPublic: isPublic
    }
    
    const response = await setBookRecordingsPublic(data)
    if (response.code === 0) {
      if (detailData.value) {
        detailData.value.allShareable = isPublic
      }
      
      uni.showToast({
        title: isPublic ? '已设为公开' : '已设为私有',
        icon: 'success'
      })
    }
  } catch (error) {
    console.error('设置公开状态失败:', error)
    uni.showToast({
      title: '设置失败',
      icon: 'none'
    })
  }
}

// 分享配音
const shareRecording = async () => {
  try {
    if (!detailData.value) return

    // 生成分享卡片
    if (shareCanvasRef.value) {
      uni.showLoading({ title: '生成分享卡片中...' })
      showShareCanvas.value = true
      await shareCanvasRef.value.generateShareCard()
    } else {
      // 降级到原有分享方式
      await fallbackShare()
    }
  } catch (error) {
    uni.hideLoading()
    console.error('分享配音失败:', error)
    uni.showToast({
      title: '分享失败',
      icon: 'none'
    })
  }
}

// 降级分享方式
const fallbackShare = async () => {
  try {
    const response = await generateBookRecordingShare(bookId.value)
    if (response.code === 0 && response.data) {
      const shareData = response.data
      shareImageUrl.value = shareData.shareImage

      uni.showToast({
        title: '请点击右上角分享',
        icon: 'none',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('获取分享信息失败:', error)
    uni.showToast({
      title: '分享失败',
      icon: 'none'
    })
  }
}

// 分享卡片生成成功回调
const onShareCardGenerated = (imageUrl: string) => {
  uni.hideLoading()
  shareImageUrl.value = imageUrl
  showShareCanvas.value = false

  uni.showToast({
    title: '请点击右上角分享',
    icon: 'none',
    duration: 2000
  })

  console.log('配音分享卡片生成成功:', imageUrl)
}

// 分享卡片生成失败回调
const onShareCardError = async (error: any) => {
  uni.hideLoading()
  showShareCanvas.value = false
  console.error('生成配音分享卡片失败:', error)

  // 降级到原有分享方式
  await fallbackShare()
}

// 格式化时间
const formatTime = (seconds: number): string => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 格式化录制时间
const formatRecordTime = (timeStr?: string): string => {
  if (!timeStr) return ''
  
  const date = new Date(timeStr)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${month}-${day}`
  }
}

// 微信分享配置
onShareAppMessage(() => {
  if (detailData.value) {
    const data = detailData.value
    return {
      title: `我完成了《${data.bookTitle}》的配音，进度${data.completionPercentage}%，快来听听吧！`,
      path: `/pages/dubbing-detail/index?bookId=${bookId.value}&shared=true`,
      imageUrl: shareImageUrl.value || data.coverUrl
    }
  }

  return {
    title: '我的配音作品，一起来配音绘本吧！',
    path: `/pages/dubbing-detail/index?bookId=${bookId.value}&shared=true`,
    imageUrl: shareImageUrl.value || '/static/images/default-share.png'
  }
})
</script>

<style scoped>
.dubbing-detail-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 50%, #bae6fd 100%);
  /* padding-top: 20px; */
  padding: 10px;
}

.share-btn {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: rgba(66, 187, 255, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.share-btn:active {
  transform: scale(0.9);
  background-color: rgba(66, 187, 255, 0.2);
}

.book-info-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  padding: 16px;
  margin: 8px;
  margin-top: 0px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 16px;
}

.book-cover {
  width: 80px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.cover-image {
  width: 100%;
  height: 100%;
}

.book-info {
  flex: 1;
}

.book-title {
  display: block;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 12px;
}

.progress-info {
  margin-bottom: 12px;
}

.progress-text {
  font-size: 14px;
  color: #94a3b8;
  margin-bottom: 8px;
  display: block;
}

.progress-bar {
  height: 6px;
  background-color: #f1f5f9;
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 4px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(135deg, #42bbff, #87ceeb);
  transition: width 0.3s ease;
}

.progress-percentage {
  font-size: 14px;
  color: #42bbff;
  font-weight: 600;
}

.public-setting {
  display: flex;
  align-items: center;
  gap: 12px;
}

.setting-label {
  font-size: 16px;
  color: #94a3b8;
  width: 80px;
}

.page-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 12px;
  padding: 0 16px;
  margin: 10px auto;
}

.page-item {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.page-item.active {
  border-color: #42bbff;
  background-color: rgba(66, 187, 255, 0.1);
}

.page-item:active {
  transform: scale(0.95);
}

.page-number {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.current-page-detail {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  margin: 0 16px 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.page-image {
  width: 100%;
  height: 300px;
  background-color: #f1f5f9;
}

.page-img {
  width: 100%;
  height: 100%;
}

.page-text {
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.text-content {
  font-size: 16px;
  color: #1e293b;
  line-height: 1.6;
}

.recording-controls {
  padding: 16px;
}

.recording-info {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.recording-info text {
  font-size: 14px;
  color: #94a3b8;
}

.recording-info .score {
  color: #ff9595;
  font-weight: 600;
}

.audio-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.play-btn {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #42bbff, #87ceeb);
  border-radius: 50%;
  box-shadow: 0 4px 16px rgba(66, 187, 255, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
}

.play-btn:active {
  transform: scale(0.95);
}

.progress-container {
  flex: 1;
}

.progress-container .progress-bar {
  height: 4px;
  background-color: #f1f5f9;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 4px;
}

.progress-container .progress-fill {
  height: 100%;
  background: linear-gradient(135deg, #42bbff, #87ceeb);
  transition: width 0.1s ease;
}

.time-text {
  font-size: 12px;
  color: #94a3b8;
}

.no-recording {
  padding: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 8px;
}

.no-recording-text {
  font-size: 16px;
  color: #94a3b8;
  font-weight: 500;
}

.no-recording-hint {
  font-size: 14px;
  color: #cbd5e1;
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32px;
}

.loading-text {
  font-size: 16px;
  color: #94a3b8;
}
</style>
